package com.iwith.dongmoon.util;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import org.apache.http.impl.cookie.CookieSpecBase;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

import com.iwith.dongmoon.activity.R;

public class RequestData {

	Context mContext;
	SharedPreferences mPreferences;

	DefaultHttpClient httpClient;
	CookieStore cookieStore;
	HttpContext localContext;

	String mApiUrl;
	String mApiPath;
	String mQueryString;

	private ArrayList<NameValuePair> mParameters;

	public RequestData(Context context) {
		Initialize(context, "", "", "");
	}

	public RequestData(Context context, String path, String type,
			String queryString) {
		// TODO Auto-generated method stub
		Initialize(context, path, type, queryString);
	}

	public void Initialize(Context context, String path, String type,
			String queryString) {
		mContext = context;
		mPreferences = mContext.getSharedPreferences("com.iwith.dongmoon.dong",
				Activity.MODE_PRIVATE);

		httpClient = new DefaultHttpClient();
		// cookieStore = new BasicCookieStore();
		// localContext = new BasicHttpContext();
		// localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

		mApiUrl = context.getString(R.string.api_url);
		mApiPath = path;
		mQueryString = queryString;

		mParameters = new ArrayList<NameValuePair>();
	}

	public void setApiPath(String path) {
		mApiPath = path;
		clearParameters();
	}

	public void setQueryString(String queryString) {
		mQueryString = queryString;
	}

	private void storeCookie(HttpResponse response) {
		CookieSpecBase cookieSpecBase = new BrowserCompatSpec();
		Header[] allHeaders = response.getHeaders("Set-Cookie");
		CookieOrigin origin = new CookieOrigin("dongmoonapp.com", 12504,
				"/api/", false);
		for (Header header : allHeaders) {
			try {
				List<Cookie> parse = cookieSpecBase.parse(header, origin);
				for (Cookie cookie : parse) {
					if (cookie.getName().equals("JSESSIONID")) {
						String sessionCookie = "JSESSIONID="
								+ cookie.getValue();

						SharedPreferences.Editor editor = mPreferences.edit();
						editor.putString("JSESSIONID", sessionCookie);
						editor.commit();
					}

					if (cookie.getName().equals("ACCESS-CODE")) {
						String sessionCookie = "ACCESS-CODE="
								+ cookie.getValue();

						SharedPreferences.Editor editor = mPreferences.edit();
						editor.putString("ACCESS-CODE", sessionCookie);
						editor.commit();
					}
				}
			} catch (MalformedCookieException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	// test function
	public String getGPSData() {
		String resultData = null;
		try {
			String getURL = mApiPath;
			HttpGet get = new HttpGet(getURL);

			String cookie = "";
			String sessionId = mPreferences.getString("JSESSIONID", "");
			String accessCode = mPreferences.getString("ACCESS-CODE", "");

			if (sessionId.equals("") == false) {
				cookie += sessionId;
			}

			if (accessCode.equals("") == false) {
				cookie += ";" + accessCode;
			}

			if (cookie.length() > 0) {
				get.setHeader("cookie", cookie);
			}

			HttpResponse responseGet = httpClient.execute(get, localContext);
			storeCookie(responseGet);

			HttpEntity resEntityGet = responseGet.getEntity();
			if (resEntityGet != null) {
				resultData = EntityUtils.toString(resEntityGet);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultData;

	}

	public String getDataGet() {

		String resultData = null;

		try {
			String getURL = mApiUrl + mApiPath + mQueryString;
			// getURL = URLEncoder.encode(getURL, "utf-8");
			HttpGet get = new HttpGet(getURL);

			String cookie = "";
			String sessionId = mPreferences.getString("JSESSIONID", "");
			String accessCode = mPreferences.getString("ACCESS-CODE", "");

			if (sessionId.equals("") == false) {
				cookie += sessionId;
			}

			if (accessCode.equals("") == false) {
				cookie += ";" + accessCode;
			}

			if (cookie.length() > 0) {
				get.setHeader("cookie", cookie);
			}

			HttpResponse responseGet = httpClient.execute(get, localContext);
			storeCookie(responseGet);

			HttpEntity resEntityGet = responseGet.getEntity();
			if (resEntityGet != null) {
				resultData = EntityUtils.toString(resEntityGet);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultData;
	}

	public void clearParameters() {
		mParameters.clear();
	}

	public void addParameter(String parameterName, String parameterValue) {
		if (parameterValue == null)
			throw new IllegalArgumentException("parameterValue can't be null!");

		System.out.println("addParameters parameterName : " + parameterName);
		System.out.println("addParameters parameterValue : " + parameterValue);

		mParameters.add(new BasicNameValuePair(parameterName, parameterValue));
	}

	public String getDataPost() {

		String resultData = null;

		try {
			String getURL = mApiUrl + mApiPath;
			HttpPost post = new HttpPost(getURL);

			String cookie = "";
			String sessionId = mPreferences.getString("JSESSIONID", "");
			String accessCode = mPreferences.getString("ACCESS-CODE", "");

			if (sessionId.equals("") == false) {
				cookie += sessionId;
			}

			if (accessCode.equals("") == false) {
				cookie += ";" + accessCode;
			}

			if (cookie.length() > 0) {
				post.setHeader("cookie", cookie);
			}

			UrlEncodedFormEntity entityRequest = new UrlEncodedFormEntity(
					mParameters, "UTF-8");
			post.setEntity(entityRequest);
			HttpResponse responsePost = httpClient.execute(post, localContext);
			storeCookie(responsePost);

			HttpEntity resEntityPost = responsePost.getEntity();
			if (resEntityPost != null) {
				resultData = EntityUtils.toString(resEntityPost);
			}
		} catch (MalformedURLException e) {

		} catch (IOException e) {

		}

		return resultData;
	}

}